package org.tigr.htc.common;

/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.log4j.Logger;

/**
 * This class is used to determine what the system's configured
 * limit on the number of open filehandles is. Many server applications require
 * a very robust setting for proper operation, so this class enables the application
 * to easily check what the configured value is.
 */

public class Ulimit {
	/** Get the Log4j logger for this class */
	private static final Logger logger = Logger.getLogger(Ulimit.class);

	public static int getMaxOpenFileHandles() throws Exception {
		logger.debug("In getMaxOpenFileHandles.");
		int ulimit = 0;
		logger.debug("Running");
		StringBuffer sb = new StringBuffer();
		StringBuffer sbe = new StringBuffer();
		Process p = null;
		try {
			String[] args = {"/bin/bash", "-c", "ulimit -Hn"};
			logger.debug("Running " + args.toString());
			p = Runtime.getRuntime().exec(args);
		} catch (IOException e1) {
			logger.error("Couldn't run command." + e1.getMessage());
			throw e1;
		}
		// Grab the standard out if any
		InputStream iso = p.getInputStream();
		InputStream ise = p.getErrorStream();
		BufferedInputStream stream = new BufferedInputStream(iso);
		BufferedInputStream error = new BufferedInputStream(ise);
		boolean ok = false;
		int exitValue = 999;
		
		while (!ok) {
			while (stream.available() > 0 || error.available() > 0) {
				while (stream.available() > 0) {
					char oChar = (char) stream.read();
					sb.append(oChar);
				}
				while (error.available() > 0) {
					char eChar = (char) error.read();
					sbe.append(eChar);
				}
			}
		
			try {
				exitValue = p.exitValue();
				logger.debug("Command exited with exit value: " + exitValue);
				ok = true;
			} catch (IllegalThreadStateException its) {
				int timeout = 600;
				try {
					// still running.
					Thread.sleep(300);
					timeout = timeout - 300;
					if (timeout < 0 && timeout >= -300) {
						logger.debug("Destroying the command...");
						p.destroy();
					}
					else if (timeout <0) {
						logger.warn("Command has not yet terminated.");
						Thread.sleep(1000);
					}
				} catch (InterruptedException e1) {
					// doesn't matter
				}
			}
		}
		if (ok) {
			logger.debug("Command finished running.");
			if (exitValue == 0) {
				logger.debug("Bash ulimit command finished without errors.");
			} else {
				throw new Exception("Error running ulimit. Exit value: " + exitValue);
			}
		} else {
			logger.debug("Destroying process...");
			p.destroy();
		}
		String ulimitString = sb.toString().trim();
		ulimit = Integer.parseInt(ulimitString);
		logger.debug("Returning "  + ulimit);
		return ulimit;
	}
	
	public static void main(String[] args) {
		try {
			int ulimit = getMaxOpenFileHandles();
			System.out.println("The ulimit is " + ulimit);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
